package com.jr.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/api/upload")
@CrossOrigin(origins = "*")
public class FileUploadController {
    
    @Value("${file.upload.path:C:/Users/86139/IdeaProjects/animalfinal/uploads}")
    private String uploadPath;
    
    @Value("${file.upload.max-size:5242880}")
    private long maxFileSize;
    
    @PostMapping("/image")
    @ResponseBody
    public Map<String, Object> uploadImage(@RequestParam("image") MultipartFile file) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 验证文件
            if (file.isEmpty()) {
                result.put("success", false);
                result.put("message", "请选择要上传的文件");
                return result;
            }
            
            // 验证文件类型
            if (!isValidImageType(file.getContentType())) {
                result.put("success", false);
                result.put("message", "不支持的文件类型，请选择图片文件");
                return result;
            }
            
            // 验证文件大小
            if (file.getSize() > maxFileSize) {
                result.put("success", false);
                result.put("message", "文件大小超过限制，最大支持5MB");
                return result;
            }
            
            // 生成唯一文件名
            String originalFilename = file.getOriginalFilename();
            String extension = getFileExtension(originalFilename);
            String uniqueFilename = generateUniqueFilename(extension);
            
            // 创建上传目录
            File uploadDir = new File(uploadPath);
            if (!uploadDir.exists()) {
                uploadDir.mkdirs();
            }
            
            // 保存文件
            File targetFile = new File(uploadDir, uniqueFilename);
            file.transferTo(targetFile);
            
            // 生成访问URL
            String imageUrl = "http://localhost:8889/uploads/" + uniqueFilename;
            
            result.put("success", true);
            result.put("message", "上传成功");
            result.put("imageUrl", imageUrl);
            result.put("originalName", originalFilename);
            result.put("fileSize", file.getSize());
            
        } catch (IOException e) {
            result.put("success", false);
            result.put("message", "文件保存失败: " + e.getMessage());
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "上传失败: " + e.getMessage());
        }
        
        return result;
    }
    
    // 验证图片类型
    private boolean isValidImageType(String contentType) {
        return contentType != null && (
            contentType.equals("image/jpeg") ||
            contentType.equals("image/png") ||
            contentType.equals("image/gif") ||
            contentType.equals("image/webp")
        );
    }
    
    // 获取文件扩展名
    private String getFileExtension(String filename) {
        if (filename == null || !filename.contains(".")) {
            return "";
        }
        return filename.substring(filename.lastIndexOf("."));
    }
    
    // 生成唯一文件名
    private String generateUniqueFilename(String extension) {
        return System.currentTimeMillis() + "_" + UUID.randomUUID().toString() + extension;
    }
}
